package khleuven.mondzorg.db;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.test.InstrumentationTestCase;
import khleuven.mondzorg.db.readers.EntryBuilderFactory;
import khleuven.mondzorg.db.readers.EntryBuilderType;
import khleuven.mondzorg.db.writers.OfflineSourceWritingType;
import khleuven.mondzorg.domain.DentalCareApp;
import khleuven.mondzorg.domain.Entry;
import khleuven.mondzorg.domain.EntryType;

public class OfflineReadingWritingTest extends InstrumentationTestCase {

	private DentalCareApp memory;
	
	protected void setUp() throws Exception {
		super.setUp();

		memory = DentalCareApp.getInstance();		

		File filesDir = getInstrumentation().getTargetContext().getFilesDir();
		List<String> availableFiles = Arrays.asList(filesDir.list());
		for(EntryType entry: EntryType.values()){
			String filename = entry.getOfflineFile();
	 		if(!availableFiles.contains(filename)){
    	 		File f = new File(filesDir, filename);
        		f.createNewFile();
    		}  
	 		entry.setFileOutputStream(getInstrumentation().getTargetContext().openFileOutput(filename, Context.MODE_PRIVATE));
	 		entry.setFileInputStream(getInstrumentation().getTargetContext().openFileInput(filename));
		}		
	}
	
	public void test_wegschrijven_en_uitlezen_geeft_terug_hetzelfde_resultaat() throws Exception{
		EntryBuilderFactory.createEntryBuilderAndLoad(EntryBuilderType.HARDCODED);

		ArrayList<Entry> allEntries = memory.getAllEntries();
		Collections.sort(allEntries); // stiekem ook een test voor de compareTo implementatie van Entry
		
		memory.storeOffline(OfflineSourceWritingType.GENERAL);
		
		//Log.v(LoggingKeyWords.TEST.name(),"before: "+before);
		DentalCareApp.destroyInstance();
		
		memory = DentalCareApp.getInstance();
		//String inbetween = memory.getAllDefinitions().toString();
		//Log.v(LoggingKeyWords.TEST.name(),"inbetween: "+inbetween);		
		
		EntryBuilderFactory.createEntryBuilderAndLoad(EntryBuilderType.OFFLINE);
		
		ArrayList<Entry> afterWritingEntries = memory.getAllEntries();
		Collections.sort(afterWritingEntries);
		
		assertTrue("Aantal entries in totaal moet overeenkomen", allEntries.size() == afterWritingEntries.size());
		
		for(int i=0; i < allEntries.size(); i++) {
			assertEquals("Entries from hardCoded or offline should equal each other", allEntries.get(i), afterWritingEntries.get(i));
		}
		
		//Log.v(LoggingKeyWords.TEST.name(),"after: "+after);
		allEntries.removeAll(afterWritingEntries);
		
		assertTrue("All entries should be retrieved successfully from writing them", allEntries.size() == 0);		
	}	
}